package com.okilo.online.app.lib.device

import com.google.gson.Gson
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.lib.device.util.OkiloDev1
import com.okilo.online.app.lib.device.util.OkiloDev2
import com.okilo.online.app.lib.device.util.OkiloDev3
import com.okilo.online.app.lib.device.util.OkiloDev4
import com.okilo.online.app.lib.device.util.OkiloDev5
import com.okilo.online.app.lib.device.util.OkiloDev6
import com.okilo.online.app.lib.device.util.OkiloDev7
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey

class OkiloDevManager() {
    val context = OkiloApplication.app
    val product = OkiloConfigs.OKILO_APPNAME
    val token = OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_TOKEN)

    private fun parameter1(path: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val content = fetchData()?:""

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun parameter2(path: String, key: String, fetchData: () -> String?): String? {
        if (!formatJson(path)) return null
        val data = fetchData() ?: return null
        val params = commonParameter(path).apply { put(key, data) }
        val content = Gson().toJson(params).trim()

        // TODO: 加密操作
//        val encrypted: String = EKHAesTool.encryptDefault(content)
//        return encrypted
        return content
    }

    private fun formatJson(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun commonParameter(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun gDev1(path: String) = parameter1(path) {
        OkiloDev1(context, product, token, path).gOkiloDev1Data()
    }

    fun gDev7(path: String) = parameter1(path) {
        OkiloDev7(context, product, token, path).gOkiloDev7Data()
    }

    fun gDev3(path: String) = parameter2(path, "deviceHardwareGzip") {
        OkiloDev3(context).gOkiloDev3Data()
    }

    fun gDev2(path: String, onResult: (String?) -> Unit) {
        OkiloDev2(context = context, onResult = { bd ->
            val result = parameter2(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun gDev5(path: String) = parameter2(path, "deviceWifiGzip") {
        OkiloDev5(context).gOkiloDev5Data()
    }

    fun gDev4(path: String) = parameter2(path, "deviceStorageGzip") {
        OkiloDev4(context).gOkiloDev4Data()
    }

    fun gDev6(path: String) = parameter2(path, "appListGzip") {
        OkiloDev6(context).gOkiloDev6Data()
    }
}